import  java.util.List;
import  java.util.ArrayList;

class Solution {
    public List<List<Integer>> shiftGrid(int[][] grid, int k){
        int m = grid.length;
        int n = grid[0].length;
        while(k > 0){
            int[][] data = new int[grid.length][grid[0].length];
            if(n == 1){
                int i =0;
                for(; i < m-1; i++){
                    data[i+1][0] = grid [i][0];
                }
                data[0][0] = grid[i][0];
                grid = data;
                k--;
            }else{
                for(int i =0; i < m; i++){
                    for(int j =0; j <n-1 ;j++){
                        data[i][j+1] = grid[i][j];
                    }
                }
                for(int i =0 ;i< m-1 ; i++){
                    for(int j = 0; j < n-1 ; j++){
                        data[i+1][0] = grid[i][n-1];
                    }
                }
                data[0][0] = grid[m-1][n-1];
                grid = data;
                k--;
            }
        }


        List<List<Integer>> newGrid = new ArrayList<>();
        for(int[] row: grid){
            List<Integer> listRow = new ArrayList<>();
            newGrid.add(listRow);
            for(int v:row){
                listRow.add(v);
            }
        }
        return newGrid;
    }
}
